package com.taotao.search.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.search.dao.SearchDao;
import com.taotao.search.pojo.Item;
import com.taotao.search.pojo.SearchResult;

@Repository
public class SearchDaoImpl implements SearchDao {

	@Autowired
	private SolrServer solrServer;
	
	@SuppressWarnings("unlikely-arg-type")
	@Override
	public SearchResult search(SolrQuery query) throws SolrServerException {
		SearchResult result = new SearchResult();
		
		QueryResponse queryResponse = solrServer.query(query);
		SolrDocumentList solrDocumentList = queryResponse.getResults();
		
		result.setRecordCount(solrDocumentList.getNumFound());
		Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
		
		List<Item> list2 = new ArrayList<Item>();
		
		for(SolrDocument document: solrDocumentList) {
			Item item = new Item();
			String id=(String) document.get("id");
			item.setId(Long.parseLong(id));
			
			
			String item_title=null;
			List<String> list = highlighting.get(id).get("item_title");
			if(list!=null && list.size()>0) {
				item_title=list.get(0);
			}
			else {
				item_title=(String) document.get("item_title");
			}
				
			item.setTitle(item_title);	
			
			item.setSellPoint((String) document.get("item_sell_point"));
			item.setPrice((long) document.get("item_price"));
			item.setImage((String) document.get("item_image"));
			item.setCategoryName((String) document.get("item_category_name"));
			item.setItemDesc((String) document.get("item_desc"));
			
			list2.add(item);
		}
		result.setItemList(list2);
		return result;
	}

}
